package com.neo.tiny.middle.file.storage.impl;

import cn.hutool.core.io.FileUtil;
import com.neo.tiny.middle.file.enums.StorageType;
import com.neo.tiny.middle.file.storage.AbstractStorageClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.io.InputStream;

/**
 * @Description: 本地存储实现
 * @Author: yqz
 * @CreateDate: 2022/11/14 23:10
 */
@Slf4j
@Component
public class LocalStorageImpl extends AbstractStorageClient {


    @Override
    public void store(InputStream inputStream, long contentLength, String contentType, String keyName) {
        String storagePath = getClientConfig().getLocal().getStoragePath();
        String fullPath = storagePath + keyName;
        FileUtil.writeFromStream(inputStream, fullPath);
    }

    @Override
    public String generateUrl(String keyName) {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        StringBuffer url = request.getRequestURL();
        String contextPath = request.getServletContext().getContextPath();
        String uri = url.delete(url.length() - request.getRequestURI().length(), url.length()).append(contextPath).toString();
        return uri + getClientConfig().getLocal().getAddress() + keyName;
    }

    @Override
    public Boolean support(String storageType) {
        return StorageType.LOCAL.getStorageType().equals(storageType);
    }

}
